package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 山东彩票网 开奖结果抓取
 * 主要抓取齐鲁风采23选5  <br/>
 * 历史地址:http://app.sdcp.cn/fccms/site/num/235kjgg.jsp<br/>
 * @author 
 *
 */
public class LotteryDrawFetch517WorkerOfficial extends AbstractLotteryDrawFetchWorker{

	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	protected static final String RESULT_HISTORY_LOCALITY_URL = "http://app.sdcp.cn/fccms/site/analyse/tjtQyh_New.jsp";

	protected String siteName = "山东彩票网";
	protected String lotteryScope = "山东群英会";
	protected String encoding = "GBK";

	public LotteryDrawFetch517WorkerOfficial(){
		super(LotteryType.SDQYH);
	}
	@Override
	public LotteryDraw fetchResult(String phase) {
		return null;
	}
	
	private LotteryDraw fetchLatestResultDetail() {

		String url = RESULT_HISTORY_LOCALITY_URL;
		String data = null;
		String pageInfo = "彩期为null时获取结果页面" + url;
		String logHeader = "==" + lotteryScope + "==" + siteName + "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";
		try {
			data = CoreFetcherUtils.URLGet(url, null, encoding);
		} catch (Exception e) {
			logger.error("获取html数据失败" + e.getMessage());
			return null;
		}
		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}
		return parserData(data);
	}

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
        String data = null;
        String encoding = "GBK";
        LotteryDraw lotteryDraw = new LotteryDraw();

        if (phase == null || "".equals(phase)) { //如果传入的彩期为null值 或者是最新彩期，此时通过抓取官网的缓存页面获取即可
            return fetchLatestResultDetail();
        } else {
	        phase = phaseConvertFromLecai(phase);
            try {
                Map<String, String> params = new HashMap<String, String>();
                params.put("q1", phase);
	            params.put("q2", phase);
                data = CoreFetcherUtils.URLPost(RESULT_HISTORY_LOCALITY_URL, params, encoding);
            } catch (Exception e) {
                logger.error("获取html数据失败" + e.getMessage());
                return null;
            }
        }
		String pageInfo = "结果页面" + RESULT_HISTORY_LOCALITY_URL;
		String logHeader = "==" + lotteryScope + "==" + siteName + "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";
		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}
		return parserData(data);
	}

	private LotteryDraw parserData(String data) {
		LotteryDraw lotteryDraw = new LotteryDraw();

		Parser parser = null;
		try {
			parser = Parser.createParser(data,  encoding);
		} catch (Exception e) {
			logger.error("解析html页面失败" + e.getMessage());
			return null;
		}

		NodeFilter filter = new HasAttributeFilter("class", "table_box2");
		NodeList nodeList = null;
		try {
			nodeList = parser.extractAllNodesThatMatch(filter);
			TableTag tableTag = (TableTag) nodeList.elementAt(0);
			TableRow tableRow = (TableRow)tableTag.childAt(2);
			String phase = StringUtils.trim(tableRow.childAt(0).toPlainTextString());
			String result = StringUtils.trim(tableRow.childAt(3).toPlainTextString());
			String[] resultArray = StringUtils.split(result, " ");
			String resultStr = "";
			for (String str : resultArray) {
				if (StringUtils.isNotEmpty(resultStr)) {
					resultStr += ",";
				}
				resultStr += str;
			}
			String volumeOfSales = StringUtils.trim(tableRow.childAt(4).toPlainTextString());
			phase = phaseConvertFromOfficial(phase);
			lotteryDraw.setPhase(phase);
			lotteryDraw.setLotteryType(this.getLotteryType());
			lotteryDraw.setJackpot(null);
			lotteryDraw.setResult(resultStr);
			lotteryDraw.setVolumeOfSales(volumeOfSales);
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		return lotteryDraw;
	}

	private String phaseConvertFromLecai(String phase) {
		return phase.substring(2, 8) + "K" + phase.substring(8, 11);
	}

	private String phaseConvertFromOfficial(String phase) {
		return "20" + StringUtils.replace(phase, "K" , "");
	}

	@Override
	protected String getResultDetailUrl(String phase) {
		return null;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}

}
